/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.crane.webtemplate.action;

import org.crane.webtemplate.exception.TextMessageException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hibernate.exception.ConstraintViolationException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static org.crane.webtemplate.Tokens.*;

/**
 *
 * @author CraneLeeon
 */
@Action("/Service")
@Results({
    @Result(name = "json", type = "dispatcher", location = "/WEB-INF/jsp/json.jsp"),
    @Result(name = "xml", type = "dispatcher", location = "/WEB-INF/jsp/xml.jsp")
})
public class Service extends BaseAction {

    private static final Log logger = LogFactory.getLog(Service.class);
    private Class boClass;

    @Override
    public Class getBoClass() {
        return boClass;
    }

    public void setBoClass(String boClass) throws ClassNotFoundException {
        this.boClass = Class.forName(boClass);
    }

    @Override
    public String execute() throws Exception {
        try {
            switch (this.act) {
                case ACT_SAY_HI:sayHI();break;
                case ACT_LIST:common_list();break;
                case ACT_GET:common_get();break;
                case ACT_NOTIFICATIONS:notifications();break;
            }
        } catch (TextMessageException ex) {
            this.json = new JSONObject().put("success", false)
                    .put("info", (ex.getPrefixMessage()==null? "":ex.getPrefixMessage())+getText(ex.getMessage())+(ex.getSuffixMessage()==null? "":ex.getSuffixMessage()))
                    .put("err_code", ex.getErrCode())
                    .toString();
        } catch (ConstraintViolationException ex) {
            logger.debug(ex);
            this.json = new JSONObject().put("success", false).put("info", getText("ConstraintViolationException")).toString();
        } catch (Exception ex) {
            logger.debug(ex);
            this.json = new JSONObject().put("success", false).put("info", ex).toString();
        }
        return "json";
    }

    protected void parseParamsFromJson(JSONObject jsonparam) throws Exception {
        try {
            this.setCellDataAsJson(jsonparam.getBoolean("cellDataAsJson"));
        } catch (JSONException jSONException) {
        }
        try {
            this.setFieldsForList(jsonparam.getString("fieldsForList"));
        } catch (JSONException jSONException) {
        }
        try {
            this.setSidx(jsonparam.getString("sidx"));
        } catch (JSONException jSONException) {
        }
        try {
            this.setSord(jsonparam.getString("sord"));
        } catch (JSONException jSONException) {
        }
        try {
            this.setPage(jsonparam.getInt("page"));
        } catch (JSONException jSONException) {
        }
        try {
            this.setRows(jsonparam.getInt("rows"));
        } catch (JSONException jSONException) {
        }
        try {
            this.setSearchField(jsonparam.getString("searchField"));
        } catch (JSONException jSONException) {
        }
        try {
            this.setSearchOper(jsonparam.getString("searchOper"));
        } catch (JSONException jSONException) {
        }
        try {
            this.setSearchString(jsonparam.getString("searchString"));
        } catch (JSONException jSONException) {
        }

    }

    protected void common_list() throws Exception {
        JSONObject jsonparam = this.getJsonObject();
        if (jsonparam != null) {
            try {
                this.boClass = Class.forName(jsonparam.getString("boClass"));
            } catch (JSONException jSONException) {
            }
            parseParamsFromJson(jsonparam);
        }
        this.json = this.listAsJSON().toString();
    }
    
    protected void common_get() throws Exception {
        JSONObject jsonparam = this.getJsonObject();
        if (jsonparam != null) {
            try {
                this.boClass = Class.forName(jsonparam.getString("boClass"));
            } catch (JSONException jSONException) {
            }
            parseParamsFromJson(jsonparam);
        }
        this.json = this.getBOAsJSON().toString();
    }

    @Override
    protected void delete() throws Exception {
    }

    @Override
    protected void save() throws Exception {
        
    }
    
    

    protected void sayHI() throws Exception {
        this.json = new JSONObject().put("success", true).put("info", "").toString();
    }

    private void notifications() throws Exception {
        this.json = new JSONObject()
                .put("success", true)
                .put("info", "this is notification!")
                .put("numbers", 0)
                .put("rows", 
                    new JSONArray()
                            .put(new JSONObject()
                                    .put("title", "test")
                                    .put("content", "test!!!")
                                    .put("url", this.getHomeURL()+"/test_1.jsp")
                            )
                ).toString();
    }
}
